package hamaster.jpbc.web;

import hamaster.jpbc.mgr.UserManager;
import hamaster.jpbc.sys.IBCSystem;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * UserServlet
 */
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private Logger logger = LoggerFactory.getLogger(getClass());

	private UserManager manager;

	/**
     * @see HttpServlet#HttpServlet()
     */
    public UserServlet() {
    	manager = (UserManager) IBCSystem.getBean("userManager");
    }

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String action = request.getParameter("action");
		if (action == null || action.length() < 3) {
			response.sendError(404);
			return;
		}
		try {
			Method method = manager.getClass().getMethod(action, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(manager, request, response);
		} catch (SecurityException e) {
			logger.error("", e);
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			logger.error("", e);
			e.printStackTrace();
			response.sendError(404);
		} catch (IllegalArgumentException e) {
			logger.error("", e);
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			logger.error("", e);
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			Throwable t = e.getTargetException();
			if (t instanceof ServletException)
				throw (ServletException) t;
			if (t instanceof IOException)
				throw (IOException) t;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
}
